import React, { Component } from 'react'
import { Row, Col, Menu, Icon } from 'antd'
import { history } from 'umi'
import './index.less'

import { getTypeInfo } from '@/services/home'

const pathMapNum = { home: '1', list: '2', life: '3' }
export default class Header extends Component {
  state = {
    navArray: [],
    selectKeys: [],
    prePath: '',
  }
  componentDidMount() {
    this.getTypeInfo()
  }
  componentDidUpdate() {
    window.scrollTo(0, 0)
    const path = history.location.pathname
    if (path !== this.state.prePath) {
      let selectKeys = []
      let title = ''
      if (path.indexOf('home') !== -1) {
        selectKeys = ['1']
        title = '主页'
      } else if (path.indexOf('list') !== -1 || path.indexOf('detail') !== -1) {
        selectKeys = ['2']
        title = '文章列表'
      } else if (path.indexOf('life') !== -1) {
        selectKeys = ['3']
        title = '我的生活'
      }
      this.setState({ prePath: path, selectKeys })
      document.title = title
    }
  }

  // 获取类别名称和编号
  getTypeInfo = async () => {
    const res = await getTypeInfo()
    if (res?.data.length > 0) {
      this.setState({ navArray: res.data })
    }
  }

  // 菜单项被点击
  handleMenuClick = (e) => {
    scrollTo(0, 0)
    switch (e.key) {
      case '1':
        history.push('/home')
        break
      case '2':
        history.push('/list')
        break
      case '3':
        history.push('/life')
        break
      default:
        history.push('/404')
    }
  }
  render() {
    return (
      <div className="header">
        <Row type="flex" justify="space-between">
          <Col xs={18} sm={18} md={14} lg={15} xl={12}>
            <span className="header-logo">CoderZrf</span>
            <span className="header-txt">一个默默努力的前端小白。</span>
          </Col>
          <Col xs={0} sm={0} md={10} lg={8} xl={6}>
            <Menu mode="horizontal" key="pc-menu" onClick={this.handleMenuClick} selectedKeys={this.state.selectKeys}>
              {this.state.navArray.map((item) => (
                <Menu.Item key={item.id}>
                  <Icon type={item.icon} />
                  {item.type_name}
                </Menu.Item>
              ))}
            </Menu>
          </Col>
          <Col xs={2} sm={2} md={0} lg={0} xl={0} className="mask-menu-container">
            <Icon type="menu-fold" style={{ color: '#1E90FF', fontSize: '2rem' }} />
            <Menu
              key="mask-menu"
              mode="vertical"
              onClick={this.handleMenuClick}
              selectedKeys={this.state.selectKeys}
              className="mask-menu"
            >
              {this.state.navArray.map((item, index) => (
                <Menu.Item key={item.id}>
                  <Icon type={item.icon} />
                  {item.type_name}
                </Menu.Item>
              ))}
            </Menu>
          </Col>
        </Row>
      </div>
    )
  }
}
